package com.css.fxfzfxqh.modules.lifelineEngineering.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.constants.EvaluationObjectEnum;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.service.FxqhAssessReportService;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.service.FxqhAssessReportTemplateService;
import com.css.fxfzfxqh.modules.lifelineEngineering.entity.LifelineTaskEntity;
import com.css.fxfzfxqh.modules.lifelineEngineering.param.AddTaskParam;
import com.css.fxfzfxqh.modules.lifelineEngineering.param.FuzzyQueryParam;
import com.css.fxfzfxqh.modules.lifelineEngineering.param.PageParam;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.EstimateRepository;
import com.css.fxfzfxqh.modules.lifelineEngineering.repository.TaskManagementRepository;
import com.css.fxfzfxqh.modules.lifelineEngineering.service.TaskManagementService;
import com.css.fxfzfxqh.modules.lifelineEngineering.utils.VersionCodeUtils;
import com.css.fxfzfxqh.modules.lifelineEngineering.vo.LifelineTaskVo;
import com.css.fxfzfxqh.modules.lifelineEngineering.vo.TaskPageVo;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.service.SUserService;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TaskManagementServiceImpl implements TaskManagementService {

    @Autowired
    private TaskManagementRepository taskManagementRepository;

    @Autowired
    private VersionCodeUtils versionCodeUtils;

    @Autowired
    private SUserService userService;

    @Autowired
    private EstimateRepository estimateRepository;

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysAreaService sysAreaService;
    @Autowired
    private FxqhAssessReportTemplateService assessReportTemplateService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(AddTaskParam param) {
        LifelineTaskEntity entity = paramToEntity(param,PlatformSessionUtils.getUserId());
        if (PlatformObjectUtils.isNotEmpty(param.getId())) {
            entity.setId(param.getId());
            LifelineTaskEntity taskById = taskManagementRepository.getEntityById(param.getId());
            if (!param.getInputMethod().equals(taskById.getInputMethod())) {
                String code = taskById.getCode();
                String[] split = code.split("-");
                String version = "SMX-PG-" + (param.getInputMethod() == 1 ? "LD" : "YXC") + "-" + split[3];
                entity.setCode(version);
            } else {
                entity.setCode(taskById.getCode());
            }
            taskManagementRepository.update(entity);
            estimateRepository.deleteByTaskId(entity.getId());
            estimateRepository.deleteLineByTaskId(entity.getId());
        } else {
            setRole(entity);
            entity.setId(UUIDGenerator.getUUID());
            taskManagementRepository.save(entity);
        }
    }

    private void setRole(LifelineTaskEntity entity) {
        entity.setRole(getRole(entity));
    }


    private String getRole(LifelineTaskEntity entity) {
        String userId = PlatformSessionContext.getUserID();
        String user = userService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        if (allRole.contains(FxfzConstants.QH_GJ_ROLE))
            return "0";
        if (allRole.contains(FxfzConstants.QH_PROVINCE_ROLE)) {
            try {
                String province = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
                entity.setProvince(province);
            } catch (Exception e) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return "1";
        }
        if (allRole.contains(FxfzConstants.PH_CITY_CODE)) {
            try {
                String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId());
                String[] strings = area.split(",");
                entity.setProvince(strings[0]);
                entity.setCity(strings[1]);
            } catch (Exception e) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return "2";
        }
        if (allRole.contains(FxfzConstants.QH_COUNTY_ROLE)) {
            try {
                String area = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId() + "," + sUser.getCityId() + "," + sUser.getCountyId());
                String[] strings = area.split(",");
                entity.setProvince(strings[0]);
                entity.setCity(strings[1]);
                entity.setCounty(strings[2]);
            } catch (Exception e) {
                throw new RuntimeException("请完善当前登陆人所属省市区信息");
            }
            return "3";
        }
        return "3";
    }

    private LifelineTaskEntity paramToEntity(AddTaskParam param,String userId) {
        LifelineTaskEntity entity = new LifelineTaskEntity();
        entity.setCode(versionCodeUtils.getVersionCode(param.getInputMethod() == 1 ? "LD" : "YXC",userId));
        entity.setName(param.getName());
        entity.setInfo(param.getInfo());
        entity.setEvaluationObject(param.getEvaluationObject());
        entity.setInputMethod(param.getInputMethod());
        entity.setInfluenceField(param.getInfluenceField());
        entity.setCreateUser(PlatformSessionUtils.getUserId());
        entity.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        entity.setUpdateUser(PlatformSessionUtils.getUserId());
        entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        SUser user = assessReportTemplateService.getUser(PlatformSessionUtils.getUserId());
        entity.setCreateUserName(user.getUserName());
        entity.setDelFlag("0");
        return entity;
    }

    @Override
    public Integer getByName(String name) {
        return taskManagementRepository.getByName(name);
    }

    @Override
    public Map<String, Object> page(PageParam param, int page, int size) {
        Map<String, Object> data = taskManagementRepository.page(param, page, size);
        data.forEach((k, v) -> {
            if (k.equals("rows")) {
                if (PlatformObjectUtils.isNotEmpty(v)) {
                    List<LifelineTaskEntity> list = (List<LifelineTaskEntity>) v;
                    data.put("rows", listToPageVo(list));
                }
            }
        });
        return data;
    }

    private List<TaskPageVo> listToPageVo(List<LifelineTaskEntity> list) {
        ArrayList<TaskPageVo> pageList = new ArrayList<>();
        list.forEach(it -> {
            String user = userService.getSUser(it.getCreateUser());
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            pageList.add(TaskPageVo.builder()
                    .id(it.getId())
                    .code(it.getCode())
                    .name(it.getName())
                    .evaluationObject(EvaluationObjectEnum.getByCode(it.getEvaluationObject()))
                    .estimate(it.getEvaluationObject())
                    .inputMethod(it.getInputMethod() == 1 ? "设定烈度" : "设定地震影响场")
                    .userName(sUser.getUserName())
                    .currentTask(it.getCurrentTask()).build()
            );
        });
        return pageList;
    }

    @Override
    public LifelineTaskEntity getById(String id) {
        return taskManagementRepository.getEntityById(id);
    }

    @Override
    public LifelineTaskVo entityToVo(LifelineTaskEntity entity) {
        return LifelineTaskVo.builder()
                .id(entity.getId())
                .code(entity.getCode())
                .name(entity.getName())
                .info(entity.getInfo())
                .evaluationObject(entity.getEvaluationObject())
                .inputMethod(entity.getInputMethod())
                .influenceField(entity.getInfluenceField()).build();
    }

    @Override
    public void currentTaskById(String id) {
        String userId = PlatformSessionUtils.getUserId();
        //修改数据库current_task为1的值
        taskManagementRepository.updateCurrentTask(userId);
        taskManagementRepository.currentTaskById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        estimateRepository.deleteByTaskId(id);
        estimateRepository.deleteLineByTaskId(id);
        taskManagementRepository.deleteById(id);
    }

    @Override
    public Map<String, Object> fuzzyQuery(FuzzyQueryParam param, int page, int size) {
        Map<String, Object> data = taskManagementRepository.fuzzyQuery(param, page, size);
        data.forEach((k, v) -> {
            if (k.equals("rows")) {
                if (PlatformObjectUtils.isNotEmpty(v)) {
                    List<LifelineTaskEntity> list = (List<LifelineTaskEntity>) v;
                    data.put("rows", listToPageVo(list));
                }
            }
        });
        return data;
    }
}
